<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="商品描述：">
            <el-input v-model="listQuery.describe" class="input-width" placeholder="商品名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="店铺名称：">
            <el-input v-model="listQuery.storeName" class="input-width" placeholder="商品描述" clearable></el-input>
          </el-form-item>
          <el-form-item label="是否包邮：">
            <el-select v-model="listQuery.post" placeholder="请选择是否包邮" class="input-width" clearable>
              <el-option value="-1" label="请选择是否包邮" disabled>请选择是否包邮</el-option>
              <el-option value="1" label="是">是</el-option>
              <el-option value="0" label="否">否</el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>商品列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加</el-button>
    </el-card>

    <div class="table-container">
      <el-table ref="policyTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center" type="index">
          <!-- type=index 可以替代 scope.$index + 1 -->
        </el-table-column>
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <el-button type="success" round @click="viewsImg(scope.row.img)">预览图片</el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" align="center">
          <template slot-scope="scope">{{ scope.row.price }}</template>
        </el-table-column>
        <el-table-column label="是否包邮" align="center">
          <template slot-scope="scope">{{ scope.row.post === 1 ? '包邮' : '不包邮' }}</template>
        </el-table-column>
        <el-table-column label="商品描述" align="center">
          <template slot-scope="scope">{{ scope.row.describe }}</template>
        </el-table-column>
        <el-table-column label="店铺名称" align="center">
          <template slot-scope="scope">{{ scope.row.storeName }}</template>
        </el-table-column>
        <el-table-column label="商品销量" align="center">
          <template slot-scope="scope">{{ scope.row.sales }}</template>
        </el-table-column>
        <el-table-column label="商品评分" align="center">
          <template slot-scope="scope">{{ scope.row.grade }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog
      :title="isEdit ? '编辑商品' : '添加商品'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="goodsList"
               ref="goodsListForm"
               :rules="rules"
               label-width="150px" size="small">
        <el-form-item label="图片：">
          <el-upload
            ref="imgUpload"
            class="myUpload"
            list-type="picture-card"
            :action="actionURL"
            accept="image/*"
            :multiple="false"
            :auto-upload="false"
            :limit="1"
            :on-change="handleChange"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :on-success="handleUploadSuccess"
            style="width: 500px"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传图片，且大小不超过10M</div>
          </el-upload>
          <el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-form-item>
        <el-form-item label="商品价格：" prop="price">
          <el-input v-model="goodsList.price" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="是否包邮：">
          <el-radio-group v-model="goodsList.post">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品描述：" prop="describe">
          <el-input v-model="goodsList.describe" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="店铺名称：" prop="storeName">
          <el-input v-model="goodsList.storeName" style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="图片" :visible.sync="imgDialogVisible" style="text-align: center;">
      <img :src="list.img" alt="" width="300px" height="450px" />
    </el-dialog>
  </div>
</template>
<script>

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 5,
    describe: null,
    storeName: null,
    post: null
  };

  const defaultGoodsList = {
    id: null,
    img: null,
    price: null,
    post: 0,
    describe: null,
    storeName: null
  };

  export default {
    name: 'goodsList',
    data() {
      return {
        listQuery: Object.assign({}, defaultListQuery),
        list: [
          {
            img: null
          }
        ],
        goodsList: Object.assign({}, defaultGoodsList),
        total: null,
        listLoading: false,
        isEdit: false,
        dialogVisible: false,
        imgDialogVisible: false,
        rules: {
          price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' }
          ],
          describe: [
            { required: true, message: '请输入商品描述', trigger: 'blur' }
          ],
          storeName: [
            { required: true, message: '请输入店铺名称', trigger: 'blur' }
          ]
        },
        actionURL: this.$fileBaseURL + 'file/upload',
        dialogImageUrl: '',
        previewDialogVisible: false
      }
    },
    created() {
      this.getList();
    },
    methods: {
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${ files.length } 个文件，共选择了 ${ files.length + fileList.length } 个文件`);
      },
      beforeRemove(file) {
        return this.$confirm(`确定移除 ${ file.name } ？`);
      },
      handleChange(file) {
        let suffix = file.name.substr(file.name.indexOf('.')).toLocaleLowerCase();
        let regExp = /(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/;

        if (!regExp.test(suffix))
        {
          this.$message.error("文件类型错误，请重新添加！");
          this.$refs.imgUpload.clearFiles();
        }
        else if (file.size > 10485760)
        {
          this.$message.error("文件大于10M，添加失败，请重新添加！");
          this.$refs.imgUpload.clearFiles();
        }
      },
      submitUpload() {
        this.$refs.imgUpload.submit();
      },
      handleUploadSuccess(response) {
        this.$message.success("文件上传成功");
        this.goodsList.img = response.data;
        this.$refs['imgUpload'].clearFiles();
      },
      viewsImg(img) {
        this.imgDialogVisible = true;
        this.list.img = this.$fileBaseURL + img;
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.goodsList = Object.assign({}, defaultGoodsList);
      },
      handleDelete(index, row) {
        this.$confirm('是否要删除该数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax({
            url: '/goodsList/delete/' + row.id,
            method: 'delete',
          }).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.handleResetSearch();
            this.getList();
          });
        }).catch(() => {});
      },
      handleUpdate(index, row) {
        this.dialogVisible = true;
        this.isEdit = true;
        this.goodsList = Object.assign({}, row);
      },
      getList() {
        this.listLoading = true;
        this.$ajax({
          url: '/goodsList/list',
          method: 'get',
          params: this.listQuery
        }).then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        });
      },
      handleDialogConfirm() {
        this.$refs.goodsListForm.validate(valid => {
          if (valid) {
            this.$confirm('是否要提交?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (this.isEdit) {
                this.$ajax({
                  url: '/goodsList/update',
                  method: 'put',
                  data: this.goodsList
                }).then(response => {
                  this.$message({
                    message: '修改成功！',
                    type: 'success'
                  });
                  this.dialogVisible = false;
                  this.getList();
                })
              } else {
                this.$ajax({
                  url: '/goodsList/insert',
                  method: 'post',
                  data: this.goodsList
                }).then(response => {
                  this.$message({
                    message: '添加成功！',
                    type: 'success'
                  });
                  this.dialogVisible = false;
                  this.getList();
                })
              }
            }).catch(() => {});
          }
        })
      }
    }
  }

</script>
